<template>
  <view>
    <!-- <van-cell :title="terminalName" is-link @click="returnTerminal" custom-class="changeTerminal"
      class="changeTerminal"></van-cell> -->
    <!-- 终端详情 -->
    <view class="card">
      <view class="title">
        <view style="white-space: nowrap">{{ terminalName }} </view>
        <view class="rightTagContent">
          <span class="baseInfoBtn" @click="toBaseInfo">基本信息</span>
          <!-- <span class="tag-status">运行</span> -->

          <span v-for="status in statusList" :key="status.label" class="tag"
            :style="{'color': status.textColor,'backgroundColor': status.color, 'display': status.value === terminalStatus ? 'inline-block': 'none'}">
            {{status.label}}
          </span>
        </view>
      </view>
      <view>
        <view class="monitorTitle">
          <span class="titleIcon"></span>
          监测数据
        </view>
        <view class="monitorItem">
          <view class="monitorAddress">进水口
            <image src="/static/manage/in.png" class="monitorTypeIcon"></image>
          </view>
          <view class="waterListContent">
            <view v-for="inWater in inWaterList" :key="inWater.equNo" class="deviceItem">{{inWater.equTypeName}}
              <span class="deviceValue">{{inWater.rtd}}</span>
            </view>
          </view>
        </view>
        <view class="monitorItem">
          <view class="monitorAddress">出水口
            <image src="/static/manage/out.png" class="monitorTypeIcon"></image>
          </view>
          <view class="waterListContent">
            <view v-for="outWater in outWaterList" :key="outWater.equNo" class="deviceItem">{{outWater.equTypeName}}
              <span class="deviceValue">{{outWater.rtd}}</span>
            </view>
          </view>
        </view>
        <view class="chartOperate">
          <view class="deviceTab">
            <span v-for="equ in equTypeList" :key="equ.equType" class="defalutTab" @click="selectedEqu(equ)"
              :class="{'selectedTab': queryData.equType === equ.equType}">{{equ.equTypeName}}</span>
            <!-- <span class="defalutTab" @click="activeValue = '电导率'"
              :class="{'selectedTab': activeValue === '电导率'}">电导率</span> -->
          </view>
          <view class="dateTypeBox">
            <span class="dataLabel">时间</span>
            <view @click="openDateSelect=true" class="dateTypePicker">
              <span class="selectValue">{{ dateType }}</span>
              <van-icon name="arrow-down" class="selectIcon" />
            </view>
            <van-action-sheet :actions="dateTypeList" v-if="openDateSelect" :show="openDateSelect" title="请选择"
              @select="onSelect" @close="onClose">

              <!-- <van-picker :columns="dateTypeList" @change="onDateTypeChange" /> -->
            </van-action-sheet>
          </view>
        </view>
        <!-- 图表 :force-use-old-canvas="true" -->
        <uni-ec-canvas-vue class="uni-ec-canvas" id="uni-ec-canvas" ref="canvas" canvas-id="uni-ec-canvas"
          :ec="ech"></uni-ec-canvas-vue>

        <!-- 能耗管理 -->
        <!-- <view class="monitorTitle">
          <span class="titleIcon"></span>
          能耗管理
        </view>
        <view class="energyLsit">
          <view v-for="item in energyList" :key="item.prop" class="energyItem">
            <view>{{ item.label }}</view>
            <view class="energyValue">{{formData[item.prop]}}
              <image v-if="isShowUpIcon(item)" src="/static/manage/up.png" class="indexIcon"></image>
              <image v-if="isShowDownIcon(item)" src="/static/manage/download.png" class="indexIcon">
              </image>
            </view>
          </view>
        </view> -->
      </view>
    </view>
  </view>
</template>

<script>
import uniEcCanvasVue from '../../components/common/uni-ec-canvas/uni-ec-canvas.vue'
import * as echarts from '../../components/common/uni-ec-canvas/echarts'
let chart = null
import { geTerminalEquData, getTerminalEnergyData, getTerminalLatestData } from '@/api/manage'
export default {
  components: {
    uniEcCanvasVue
  },
  props: {
    terminalName: {
      type: String,
      required: true
    },
    terminalStatus: {
      type: Number,
      required: true
    },
    terminalId: {
      type: String,
      required: true
    },
    equList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      equLastDataList: [],
      queryData: {
        dateType: '2',
        equType: '',
        terminalId: ''
      },
      formData: {
        today: 0,
        yesterday: 0,
        month: 0,
        lastMonth: 0,
      },
      energyList: [
        { label: '今日耗能', prop: 'today' },
        { label: '昨日耗能', prop: 'yesterday' },
        { label: '本月耗能', prop: 'month' },
        { label: '上月耗能', prop: 'lastMonth' },
      ],
      openDateSelect: false,
      dateTypeList: [{ name: '当天', id: '1' }, { name: '7天', id: '2' }, { name: '30天', id: '3' }],
      dateType: '7天',
      // activeValue: '液位',
      ech: {
        lazyLoad: true
      },
      statusList: [
        { label: '运行', value: 1, color: '#E5EEFF', textColor: '#3C8AFF' },
        { label: '未运行', value: 2, color: '#E1E1E1', textColor: '#8E8E8E' }
      ],
      option: {
        legend: {
          show: true,
          icon: 'circle',
          itemWidth: 6,
          itemHeight: 6,
          top: 0,
        },
        tooltip: {
          trigger: 'axis',
          // formatter: (params, tikect) => {
          //   let str = params[0].name + '\n'
          //   //params是数组格式
          //   for (let item of params) {
          //   //设置浮层图形的样式跟随图中展示的颜色
          //     str += this.queryParams.equType + "数值\t" + item.value 
          //     // str +=  "液位高度\t" + item.value + 'cm'
          //     // str +=  "<span style='display:inline-block;width:10px;height:10px;border-radius:10px;background-color:" + item.color + ";'></span>" + "\t" + "液位高度\t" + item.value
          //   }
          //   return str
          //   // return params[0].axisValue + "<span style='display:inline-block;width:6px;height:6px;background-color:#3576F2;border-radius: 50px;margin:10px'></span>\n液位高度：" + params[0].value + 'cm'
          // }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '28%',
          top: '10%'
        },
        xAxis: {
          // type: 'category',
          type: 'time',
          // boundaryGap: false,
          boundaryGap: ['23%', '23%'],
          // 注： x轴不指定data,自动会从series取
          axisLine: {
            lineStyle: {
              color: 'rgba(24,24,24,0.25)'
            }
          },
          axisTick: {
            lineStyle: {
              color: 'rgba(24,24,24,0.25)'
            }
          },
          splitNumber: 6,
          // minInterval: 1,
          // maxInterval: 3600 * 24 * 1000,
          axisLabel: {
            interval: 'auto' // 显示所有标签
          },
          axisLabel: {
            // fomatter: (value) => {
            //   console.log(value, 'value')
            //   var date = new Date(value);
            //   var monthDay = (date.getMonth() + 1) + '-' + date.getDate(); // 月-日
            //   var year = date.getFullYear(); // 年
            //   return monthDay + '\n' + year; // 双行显示，\n 换行
            //   // var date = new Date(value[0]);
            //   // var monthDay = (date.getMonth() + 1) + '-' + date.getDate(); // 月-日
            //   // var year = date.getFullYear(); // 年
            //   // return monthDay + '\n' + year; // 双行显示，\n 换行
            // }
            formatter: this.formatter,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'rgba(24,24,24,0.1)', // 网格线颜色
              // type: 'dashed' // 线的类型，可以是 'solid', 'dashed', 或 'dotted'
            }
          },
          // data: []
          // data: ['1号', '2号', '3号', '4号', '5号', '6号']
        },
        yAxis: {
          name: '',
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            textStyle: {
              color: '#a3a3a3'
            }
          },
          nameTextStyle: {
            color: '#a3a3a3'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(24,24,24,0.1)', // 网格线颜色
              // type: 'dashed' // 线的类型，可以是 'solid', 'dashed', 或 'dotted'
            }
          }
        },
        dataZoom: [
          {},
          {
            type: 'inside'
          }
        ],
        series: [{
          name: '进水口',
          type: 'line',
          color: '#3C8AFF',
          data: [],
        }, {
          name: '出水口',
          type: 'line',
          color: '#FAE021',
          data: [],
        },
        ]
      },
    }
  },
  watch: {
    equList: {
      handler: function (val) {
        if (val.length) {
          this.queryData.equType = val[0] && val[0].equType
          // this.activeValue = val[0].equNo
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    inWaterList() {
      return this.equLastDataList.filter(equ => equ.impExp === 1)
    },
    outWaterList() {
      return this.equLastDataList.filter(equ => equ.impExp === 2)
    },
    equTypeList() {
      const newList = []
      const equTypeList = []
      this.equList.forEach((acc, index) => {
        if (!equTypeList.includes(acc.equType)) {
          console.log(acc, '筛选中....', index)
          equTypeList.push(acc.equType)
          newList.push(acc)
        }
      })
      console.log(newList, 'equTypeList-计算属性')
      return newList
    },
  },
  onReady() {
  },
  mounted() {
    this.getTerminalLatestData()
    // this.getTerminalEnergyData()

    this.$nextTick(() => {
      setTimeout(() => {
        console.log(this.$refs.canvas, 'this.$refs.canvas')
        if (this.$refs.canvas) {
          this.$refs.canvas.init(this.initChart)
          this.geTerminalEquData()
        }
      }, 1000)
    })
  },
  methods: {
    formatter(value) {
      // console.log(value, '图表x轴刻度')
      let xAxisLabel = "";
      if (this.queryData.dateType === '1') {
        xAxisLabel = new Date(value).format("hh:mm");
      } else if (this.queryData.dateType === '2') {
        xAxisLabel = new Date(value).format("MM-dd");
      } else {
        xAxisLabel = new Date(value).format("dd");
      }
      return xAxisLabel;
    },
    isShowUpIcon(item) {
      const filter1 = ['昨日耗能', '上月耗能'].includes(item.label)
      const filter2 = item.label === '昨日耗能' && this.formData.today > this.formData.yesterday ? true :
        item.label === '上月耗能' && this.formData.month > this.formData.lastMonth ? true : false
      return filter2
    },
    isShowDownIcon(item) {
      const filter1 = ['昨日耗能', '上月耗能'].includes(item.label)
      const filter2 = item.label === '昨日耗能' && this.formData.today < this.formData.yesterday ? true :
        item.label === '上月耗能' && this.formData.month < this.formData.lastMonth ? true : false
      return filter2
    },
    // 获取设备最新值
    getTerminalLatestData() {
      getTerminalLatestData({ terminalId: this.terminalId }).then(({ data }) => {
        console.log(data, 'data-设备监测数据')
        this.equLastDataList = data.data
      })
    },
    // 获取终端能耗
    getTerminalEnergyData() {
      getTerminalEnergyData({ terminalId: this.terminalId }).then(({ data }) => {
        console.log('data-获取终端能耗数据', data)
        this.formData = data.data
      })
    },
    selectedEqu(equ) {
      console.log(equ, 'equ')
      // this.activeValue = equ.equNo
      this.queryData.equType = equ.equType
      this.geTerminalEquData()
    },
    // 根据终端id查询设备实时数据
    geTerminalEquData() {
      this.queryData = {
        ...this.queryData,
        terminalId: this.terminalId,
      }
      geTerminalEquData({ ...this.queryData }).then(({ data }) => {
        console.log(data.data, 'data--设备实时数据')
        const that = this
        // let data = {
        //   inWaterList: [{reportTime: '2025-07-01',rtd:100}, {reportTime: '2025-07-02',rtd:200}, {reportTime: '2025-07-03',rtd:220}, {reportTime: '2025-07-04',rtd:102}, {reportTime: '2025-07-05',rtd:239}, {reportTime: '2025-07-06',rtd:112}],
        //   outWaterList: [{reportTime: '2025-07-01',rtd:220}, {reportTime: '2025-07-02',rtd:130}, {reportTime: '2025-07-03',rtd:140}, {reportTime: '2025-07-04',rtd:160}, {reportTime: '2025-07-05',rtd:120}, {reportTime: '2025-07-06',rtd:220}]
        // }
        // let dates = (new Date(this.queryParams.endTime) - new Date(this.queryParams.startTime)) / (24 * 60 * 60 * 1000)
        const operatorArr = []
        const markLineData = []
        const { inOperatorType, inThreshold, inMaxThre, outOperatorType, outThreshold, outMaxThre } = data.data
        if ([1, 2, 4].includes(inOperatorType)) {
          operatorArr.push({
            name: '(进)',
            value: inThreshold
          })
        } else if (inOperatorType == 3) {
          operatorArr.push({
            name: '(进)',
            value: [inThreshold, inMaxThre]
          })
        }
        if ([1, 2, 4].includes(outOperatorType)) {
          operatorArr.push({
            name: '(出)',
            value: outThreshold
          })
        } else if (outOperatorType == 3) {
          operatorArr.push({
            name: '(出)',
            value: [outThreshold, outMaxThre]
          })
        }
        console.log('终端阈值', operatorArr)
        operatorArr.forEach(item => {
          if (typeof (item.value) === 'number') {
            const valueArr = markLineData.map(item1 => item1.yAxis)
            if (!valueArr.includes(item.value)) {
              markLineData.push(
                {
                  name: `${item.name}`,
                  yAxis: item.value,
                  lineStyle: {
                    type: 'dashed',
                    color: 'transparent',
                    dashOffset: 5
                  },
                  label: {
                    show: true,
                    position: 'end',
                    color: 'red',
                    fontWeight: 'bold',
                    distance: 0,
                    formatter: (params) => {
                      console.log(params, '阈值渲染')
                      return params.name
                    }
                  }
                },
                {
                  name: `警戒值`,
                  yAxis: item.value,
                  lineStyle: {
                    type: 'dashed',
                    color: '#FF0000',
                    dashOffset: 5
                  },
                  label: {
                    show: true,
                    position: 'start',
                    color: 'red',
                    fontWeight: 'bold',
                    distance: 0,
                    formatter: (params) => {
                      return params.value
                    }
                  }
                }
              )
            } else {
              markLineData[0].name = '警戒线'
            }
            console.log(markLineData, 'markLineData')
          }
        })

        const inValueList = data.data.inWaterList.map(item => item.rtd)
        const outValueList = data.data.outWaterList.map(item => item.rtd)
        const maxvalue = Math.max(...inValueList) > Math.max(...outValueList) ? Math.max(...inValueList) :
          Math.max(...inValueList) < Math.max(...outValueList) ? Math.max(...outValueList) : Math.max(...inValueList)
        const minvalue = Math.min(...inValueList) > Math.min(...outValueList) ? Math.min(...outValueList) :
          Math.min(...inValueList) < Math.min(...outValueList) ? Math.min(...inValueList) : Math.min(...outValueList)
        const marklineData1 = markLineData.map(item => item.yAxis)
        const maxarr = Math.max(...marklineData1, maxvalue)
        const minarr = Math.min(...marklineData1, minvalue)
        console.log(maxarr, minarr, marklineData1, '最大最小值')
        // if (data.data?.operatorType === 3) {
        //   const min = data.data?.threshold > minvalue ? minvalue : data.data?.threshold
        //   const max = data.data?.maxThre > maxvalue ? data.data?.threshold : maxvalue
        //   this.option.yAxis.min = min >= 0 ? 0 : min
        //   if (max) this.option.yAxis.max = max

        // } else {
        //   const max = data.data?.threshold > maxvalue ? data.data?.threshold : maxvalue
        this.option.yAxis.interval = maxarr < 1 ? 0.1 :
          maxarr > 1 && maxarr <= 10 ? 2 :
            maxarr > 10 && maxarr <= 20 ? 5 :
              maxarr > 10 && maxarr <= 50 ? 10 :
                maxarr > 50 && maxarr <= 100 ? 20 :
                  maxarr > 100 && maxarr <= 350 ? 50 :
                    maxarr > 350 && maxarr <= 700 ? 100 :
                      maxarr > 700 ? 200 : 1
        if (maxarr) this.option.yAxis.max = maxarr < 1 ? maxarr.toFixed(1) : Math.ceil(maxarr / this.option.yAxis.interval) * this.option.yAxis.interval

        this.option.series[0].data = data.data.inWaterList.map(function (item, index) {
          return [item.reportTime, Number(item.rtd)]
          // return Number(item.rtd);
        })
        this.option.series[1].data = data.data.outWaterList.map(function (item, index) {
          return [item.reportTime, Number(item.rtd)]
          // return Number(item.rtd);
        })
        console.log(this.option, chart, '渲染图表')
        this.option.series[0].markLine = {
          symbol: 'none',
          data: markLineData,
          lineStyle: {
            width: 2
          }
        }
        chart.setOption(this.option)

      })
    },
    toBaseInfo() {
      this.$tab.navigateTo(`/subpack_Manage_VillageDetail/villageDetail/baseInfo?id=${this.terminalId}`)
    },
    onSelect(event) {
      console.log(event, '选中')
      this.dateType = event.detail.name
      this.queryData.dateType = event.detail.id
      this.openDateSelect = false
      this.geTerminalEquData()
    },
    onClose() {
      this.openDateSelect = false
    },
    onDateTypeChange(date) {
      console.log(date, '选中日期格式')
    },
    returnTerminal() {
      console.log('触发')
      uni.$emit('returnTerminal', { selected: false })
    },
    initChart(canvas, width, height, canvasDpr) {
      console.log('初始化图表', chart)
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: canvasDpr
      })
      canvas.setChart(chart)
      chart.setOption(this.option)
      return chart
    },
  }
}
</script>

<style lang="scss" scoped>
.uni-ec-canvas {
  width: 100%;
  height: 600rpx;
  display: block;
  margin-bottom: 48rpx;
}
.energyLsit {
  display: flex;
  justify-content: space-between;
  margin-bottom: 48rpx;
  padding: 0 18rpx;
  .energyItem {
    text-align: left;
    font-weight: bold;
    font-size: 28rpx;
    color: #4a4a4a;
    line-height: 40rpx;
    .energyValue {
      font-weight: 800;
      font-size: 32rpx;
      color: #3c8aff;
      line-height: 44rpx;
      .indexIcon {
        width: 22rpx;
        height: 27rpx;
        margin-left: 24rpx;
      }
    }
  }
}
.monitorTitle {
  font-weight: 800;
  font-size: 28rpx;
  color: #4a4a4a;
  line-height: 40rpx;
  margin: 32rpx 0;
  .titleIcon {
    display: inline-block;
    width: 8rpx;
    height: 20rpx;
    background: #2769f7;
    border-radius: 6rpx;
    opacity: 0.6;
    margin: 0 16rpx;
  }
}
.chartOperate {
  display: flex;
  justify-content: space-between;
  .dateTypeBox {
    display: flex;
    font-weight: bold;
    font-size: 28rpx;
    color: #5e5e5e;
    line-height: 40rpx;
    margin: 36rpx 0;
    align-items: top;
    .dataLabel {
      height: 56rpx;
      white-space: nowrap;
      line-height: 56rpx;
    }
    .dateTypePicker {
      width: 180rpx;
      height: 56rpx;
      background: #f2f6f7;
      border-radius: 32rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #4a4a4a;
      line-height: 34rpx;
      margin-left: 16rpx;
      position: relative;
      .selectIcon {
        position: absolute;
        right: 6rpx;
        top: 20rpx;
      }
    }
    .selectValue {
      line-height: 56rpx;
      margin-left: 20rpx;
    }
  }
}
.deviceTab {
  margin: 36rpx 0;
  .defalutTab {
    display: inline-block;
    border-radius: 6rpx;
    border: 1rpx solid #2769f7;
    // opacity: 0.5;
    font-weight: bold;
    font-size: 24rpx;
    color: #3c8aff;
    line-height: 34rpx;
    padding: 4rpx 12rpx;
    margin-left: 12rpx;
  }
  .selectedTab {
    background: #2769f7;
    color: #ffffff !important;
  }
}
.monitorItem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .waterListContent {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-left: 18rpx;
    width: 75%;
  }
  .deviceItem {
    font-weight: bold;
    font-size: 24rpx;
    color: #686868;
    line-height: 34rpx;
    margin: 12rpx 0;
    display: flex;
    flex-direction: column;
    flex: 1;
    .deviceValue {
      font-weight: 800;
      font-size: 32rpx;
      color: #7b9ce3;
      line-height: 44rpx;
      // margin-left: 28rpx;
    }
  }

  .monitorAddress {
    font-weight: 800;
    font-size: 28rpx;
    color: #4a4a4a;
    line-height: 40rpx;
    white-space: nowrap;
    .monitorTypeIcon {
      width: 24rpx;
      height: 24rpx;
      margin-left: 16rpx;
      vertical-align: middle;
    }
  }
}
::v-deep .changeTerminal {
  text-align: left;
  //  .van-cell{
  border-radius: 10rpx;
  // }
}

.card {
  margin-top: 16rpx;
  background: #fff;
  padding: 24rpx 28rpx;
  border-radius: 6rpx;
  text-align: left;
  font-weight: 800;
  font-size: 32rpx;
  color: #4a4a4a;
  line-height: 44rpx;
  .title {
    // position: relative;
    display: flex;
    justify-content: space-between;
    .baseInfoBtn {
      padding: 4rpx 18rpx;
      font-weight: bold;
      font-size: 24rpx;
      color: #ffffff;
      line-height: 42rpx;
      background: #2769f7;
      margin-right: 12rpx;
      border-radius: 6rpx;
      // margin-left: 32rpx;
    }
    .rightTagContent {
      // position: absolute;
      // right: 0;
      // top: 0;
      text-align: right;
      white-space: wrap;
      .tag {
        display: inline-block;
        padding: 0rpx 24rpx;
        border-radius: 6rpx;
        font-size: 24rpx;
        line-height: 42rpx;
      }
    }
  }
}
</style>